package com.yuexiang.melodyhub.gateway.filter.security;

import com.yuexiang.melodyhub.common.constant.UsualConstant.BizConstant;
import com.yuexiang.melodyhub.common.result.ReturnCode;
import com.yuexiang.melodyhub.common.utils.JwtUtil;
import com.yuexiang.melodyhub.gateway.exception.ValidException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class TokenValidationProcessor extends AuthProcessor {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public Mono<Void> process(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getHeaders().getFirst(BizConstant.TOKEN_HEADER);
        if (token == null || !token.startsWith(BizConstant.TOKEN_TYPE))
            return ValidException.unauthorized(exchange, ReturnCode.UNAUTHORIZED.getMsg());

        token = token.substring(BizConstant.TOKEN_TYPE.length());
        if (!JwtUtil.isTokenValid(token))
            return ValidException.unauthorized(exchange, ReturnCode.TOKEN_IS_INVALID.getMsg());
        if (!isTokenValid(token)) return ValidException.unauthorized(exchange, ReturnCode.TOKEN_IS_INVALID.getMsg());
        try {
            exchange.getRequest().mutate()
                    .header(BizConstant.HEADER_USERNAME, JwtUtil.getUsername(token))
                    .header(BizConstant.HEADER_ROLES, String.join(",", JwtUtil.getAuthorities(token)))
                    .build();

            return next.process(exchange, chain);
        } catch (Exception e) {
            return ValidException.unauthorized(exchange, ReturnCode.TOKEN_IS_INVALID.getMsg());
        }
    }

    private boolean isTokenValid(String token) {
        String redisToken = redisTemplate.opsForValue().get(BizConstant.TOKEN_CACHE_PREFIX + JwtUtil.getUsername(token));
        if (!StringUtils.hasLength(redisToken)) return false;
        return redisToken.equals(token);
    }

}
